package com.jmda.platform.engine.worklist.action;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jmda.platform.commom.HttpRequestParamParser;
import com.jmda.platform.commom.LocalCacheManager;
import com.jmda.platform.commom.SpringContextUtil;
import com.jmda.platform.database.DataBaseService;
import com.jmda.platform.engine.mybatis.DataPager;
import com.jmda.platform.engine.mybatis.MybatisEngine;
import com.jmda.platform.engine.worklist.event.WorkListFormatEvent;
import com.jmda.platform.repository.ResositoryException;
import com.jmda.platform.repository.RespositoryConstant;
import com.jmda.platform.repository.worklist.model.ColumnModel;
import com.jmda.platform.repository.worklist.model.ExtColumnModel;
import com.jmda.platform.repository.worklist.model.WorkListModel;
import com.jmda.platform.repository.worklist.service.WorkListService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/execute/worklist/ext")
public class WorkListEngineController {
    @Resource
    WorkListService workListService;
    @Resource
    DataBaseService db;
    @Resource
    MybatisEngine mybatis;
    private static final String list_rightTree = "list_rightTree";
    private static final String leftTree_list = "leftTree_list";
    private static final String leftTree_list_rightTree = "leftTree_list_rightTree";

    @RequestMapping(value = "/getPage", method = {RequestMethod.POST, RequestMethod.GET})
    public String getPage(String worklistId, HttpServletRequest request, ModelMap map) throws ResositoryException {
        Map<String, Object> paramsMap = HttpRequestParamParser.formatParam(request);
        FreeMarkerConfigurer freeMarkerConfigurer = SpringContextUtil.getBean("freemarkerConfig");
        WorkListModel worklistModel = workListService.get(worklistId);
        List<ColumnModel> columnList = worklistModel.getColumn();
        StringBuffer datasparams = new StringBuffer();
        for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
            String key = entry.getKey().toString();
            String value = entry.getValue().toString();
            if (!key.equals("worklistId")) {
                datasparams.append("&").append(key).append("=").append(value);
            }
        }
        // TODO 执行 表格格式化事件
        if (worklistModel.getFormateClass() != null && worklistModel.getFormateClass().trim().length() > 0) {
            try {
                List<ExtColumnModel> extColumnList = new ArrayList<>();
                Class<WorkListFormatEvent> eventClass = (Class<WorkListFormatEvent>) Class.forName(worklistModel.getFormateClass());
                WorkListFormatEvent event = SpringContextUtil.getBean(eventClass);
                if (event != null) {
                    event.formatColumnModel(extColumnList);
                }
                map.put("extColumnList", extColumnList);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                System.err.println("不存在[" + worklistModel.getFormateClass() + "]java类，或是该类没有实现[com.jmda.platform.engine.worklist.event.WorkListFormatEvent]接口");
                e.printStackTrace();
            }
        }
        map.put("columnList", columnList);
        map.put("isChecked", "true");
        if (columnList != null && columnList.size() > 0) {
            for (ColumnModel columnModel : columnList) {
                if (columnModel.getColspan() > 0 || columnModel.getRowspan() > 0) {
                    map.put("isChecked", "false");
                    break;
                }
            }
        }
        if (worklistModel.getButton() != null && worklistModel.getButton().size() > 0) {
            map.put("buttons", worklistModel.getButton());
        }

        map.put("searchs", worklistModel.getSearchWhere());
        String basePath = request.getContextPath();
        String extMeata = worklistModel.getExtendJavascript() == null ? "" : worklistModel.getExtendJavascript().replaceAll("\\$\\{basePath\\}", basePath);
        String personContextStr = LocalCacheManager.getContextJsParams();
        map.put("extMeta", personContextStr + extMeata);
        map.put("pageSize", worklistModel.getPage_size() < 10 ? 30 : worklistModel.getPage_size());
        map.put("worklistId", worklistId);
        map.put("dataparams", datasparams);
        map.put("basePath", basePath);
        String templateFile = worklistModel.getTemplateFile();
        if (templateFile != null && templateFile.equals(list_rightTree)) {
            map.put("rightUrl", worklistModel.getRightUrl());
            map.put("rightTitle", worklistModel.getRightTitle());
        } else if (templateFile != null && templateFile.equals(leftTree_list)) {
            map.put("leftUrl", worklistModel.getLeftUrl());
            map.put("leftTitle", worklistModel.getLeftTitle());
        } else if (templateFile != null && templateFile.equals(leftTree_list_rightTree)) {
            map.put("rightUrl", worklistModel.getRightUrl());
            map.put("rightTitle", worklistModel.getRightTitle());
            map.put("leftUrl", worklistModel.getLeftUrl());
            map.put("leftTitle", worklistModel.getLeftTitle());
        }
        map.put("templateFile", templateFile);
        if (worklistModel.getIs_page() != null && worklistModel.getIs_page() == true) {
            map.put("is_page", "false");
            map.put("urlMethod", "getAllDatas");
        } else {
            map.put("is_page", "true");
            map.put("urlMethod", "getDatas");
        }
        if (worklistModel.getIs_execute_query() != null && worklistModel.getIs_execute_query() == true) {
            map.put("is_execute_query", "false");
        } else {
            map.put("is_execute_query", "true");
        }
        if (worklistModel.getIs_detail() != null && worklistModel.getIs_detail() == true) {
            map.put("groupHtml", "view: detailview, detailFormatter:function(rowIndex, rowData){ if (typeof (" + worklistModel.getXieyin_code() + "_detailFormatter) != 'undefined'){ return " + worklistModel.getXieyin_code() + "_detailFormatter(rowIndex, rowData);}else {return '';  } },");
        }
        return "/system/sys_worklist_easyui";
    }

    /**
     * 分页grid SQL
     *
     * @param worklistId
     * @param page
     * @param rows
     * @param searchConditions
     * @param fuzzyCondition
     * @param request
     * @return
     * @throws ResositoryException
     * @throws JsonProcessingException
     * @throws SQLException
     */
    @RequestMapping(value = "/getDatas", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String getDatas(String worklistId, int page, int rows, String searchConditions, String fuzzyCondition, HttpServletRequest request) throws ResositoryException, JsonProcessingException, SQLException {
        ObjectMapper mapper = new ObjectMapper();
        String bool = request.getParameter("search_is_execute_query");
        Map<String, Object> requestParams = HttpRequestParamParser.formatParam(request);
        String oldSort = (String) requestParams.get("sort");
        if (oldSort != null && oldSort.indexOf("_Desc") != -1) {
            String newSort = oldSort.substring(0, oldSort.indexOf("_Desc"));
            requestParams.replace("sort", newSort);
        }
        WorkListModel worklistModel = workListService.get(worklistId);
        //默认不执行查询
        boolean _bool = true;
        if (worklistModel != null && worklistModel.getIs_execute_query() != null && worklistModel.getIs_execute_query() == true) {
            _bool = false;
        }
        if (bool != null) {
            _bool = true;
        }
        if (_bool) {
            Map<String, Object> params = LocalCacheManager.getContextParams();
            params.putAll(requestParams);
            DataPager<Map<String, Object>> dataPage = mybatis.selectList(worklistModel.getId(), RespositoryConstant.WORKLIST_RUNTIME_QUERY_LIST_ID, params, rows, page);
            List<ColumnModel> columnList = worklistModel.getColumn();
            if (columnList != null) {
                for (ColumnModel columnModel : columnList) {
                    if (columnModel.getRef_type() != null) {
                        for (Map<String, Object> record : dataPage.getRows()) {
                            String value = String.valueOf(record.get(columnModel.getColumnName()));
                            if (value != null && !value.equals("null") && value.trim().length() > 0) {
                                record.put(columnModel.getColumnName() + "_Desc", LocalCacheManager.referenceData("redis", value, columnModel.getRef_params()));
                            }
                        }

                    }
                }
            }
            // TODO 执行 表格格式化事件
            if (worklistModel.getFormateClass() != null && worklistModel.getFormateClass().trim().length() > 0) {
                try {
                    List<ExtColumnModel> extColumnList = new ArrayList<>();
                    Class<WorkListFormatEvent> eventClass = (Class<WorkListFormatEvent>) Class.forName(worklistModel.getFormateClass());
                    WorkListFormatEvent event = SpringContextUtil.getBean(eventClass);
                    if (event != null) {
                        event.formatColumnModel(extColumnList);
                        event.formatRecords(extColumnList, dataPage.getRows());
                    }
                } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    System.err.println("不存在[" + worklistModel.getFormateClass() + "]java类，或是该类没有实现[com.jmda.platform.engine.worklist.event.WorkListFormatEvent]接口");
                    e.printStackTrace();
                }
            }
            Map<String, Object> json = new HashMap<String, Object>();
            if (dataPage.getRows() == null) {
                json.put("rows", "[]");
                json.put("total", 0);
            } else {
//    			int total = mybatis.getListCount(worklistModel.getId(), RespositoryConstant.WORKLIST_RUNTIME_QUERY_COUNT_ID, params);
                json.put("rows", dataPage.getRows());
                json.put("total", dataPage.getTotal());
            }
            return mapper.writeValueAsString(json);
        } else {
            Map<String, Object> json = new HashMap<String, Object>();
            json.put("rows", "[]");
            json.put("total", 0);
            return mapper.writeValueAsString(json);
        }
    }

    /**
     * 分页grid SQL
     *
     * @param worklistId
     * @param searchConditions
     * @param fuzzyCondition
     * @param request
     * @return
     * @throws ResositoryException
     * @throws JsonProcessingException
     * @throws SQLException
     */
    @RequestMapping(value = "/getAllDatas", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String getAllDatas(String worklistId, String searchConditions, String fuzzyCondition, HttpServletRequest request) throws ResositoryException, JsonProcessingException, SQLException {
        String bool = request.getParameter("search_is_execute_query");
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> requestParams = HttpRequestParamParser.formatParam(request);
        WorkListModel worklistModel = workListService.get(worklistId);
        //默认不执行查询
        boolean _bool = true;
        if (worklistModel != null && worklistModel.getIs_execute_query() != null && worklistModel.getIs_execute_query() == true) {
            _bool = false;
        }
        if (bool != null) {
            _bool = true;
        }
        if (_bool) {
            Map<String, Object> params = LocalCacheManager.getContextParams();
            params.putAll(requestParams);
            List<Map<String, Object>> dataPage = mybatis.selectList(worklistModel.getId(), RespositoryConstant.WORKLIST_RUNTIME_QUERY_LIST_ID, params);
            List<ColumnModel> columnList = worklistModel.getColumn();
            if (columnList != null) {
                for (ColumnModel columnModel : columnList) {
                    if (columnModel.getRef_type() != null) {
                        for (Map<String, Object> record : dataPage) {
                            String value = String.valueOf(record.get(columnModel.getColumnName()));
                            if (value != null && !value.equals("null") && value.trim().length() > 0) {
                                record.put(columnModel.getColumnName() + "_Desc", LocalCacheManager.referenceData("redis", value, columnModel.getRef_params()));
                            }
                        }

                    }
                }
            }
            // TODO 执行 表格格式化事件
            if (worklistModel.getFormateClass() != null && worklistModel.getFormateClass().trim().length() > 0) {
                try {
                    List<ExtColumnModel> extColumnList = new ArrayList<>();
                    Class<WorkListFormatEvent> eventClass = (Class<WorkListFormatEvent>) Class.forName(worklistModel.getFormateClass());
                    WorkListFormatEvent event = SpringContextUtil.getBean(eventClass);
                    if (event != null) {
                        event.formatColumnModel(extColumnList);
                        event.formatRecords(extColumnList, dataPage);
                    }
                } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    System.err.println("不存在[" + worklistModel.getFormateClass() + "]java类，或是该类没有实现[com.jmda.platform.engine.worklist.event.WorkListFormatEvent]接口");
                    e.printStackTrace();
                }
            }
            //Map<String, Object> json = new HashMap<String, Object>();
            if (dataPage == null || dataPage.size() == 0) {
                // json.put("rows", "[]");
                // json.put("total", 0);
                return "[]";
            } else {
//    			int total = mybatis.getListCount(worklistModel.getId(), RespositoryConstant.WORKLIST_RUNTIME_QUERY_COUNT_ID, params);
                // json.put("rows", dataPage);
                // json.put("total", dataPage.size());
                return mapper.writeValueAsString(dataPage);
            }
        } else {
            return "[]";
        }


    }

}
